import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_markdown/flutter_markdown.dart' as md;
import 'package:jg_docs/utils.dart/utils.dart';

class DocsPage extends StatefulWidget {
  const DocsPage({Key? key}) : super(key: key);

  @override
  _DocsPageState createState() => _DocsPageState();
}

class _DocsPageState extends State<DocsPage> {
  late Future<String> markDown;
  late bool isDartFile;
  @override
  void initState() {
    super.initState();
    TopicCenter().listen<String>(
      _loadDocsFromPath,
      onChannel: TopicChannel.docs,
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadDocsFromPath('README.md');
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<String>(
      future: markDown,
      builder: (context, snapShot) {
        switch (snapShot.connectionState) {
          case ConnectionState.done:
            String markdownText = isDartFile ? '```dart\n${snapShot.data!}\n```' : snapShot.data!;
            var controller = markdownText.length > 30 ? ScrollController() : null;
            return md.Markdown(
              data: markdownText,
              controller: controller,
            );
          default:
            return CircularProgressIndicator();
        }
      },
    );
  }

  void _loadDocsFromPath(String docsPath) {
    markDown = rootBundle.loadString(docsPath);
    isDartFile = docsPath.endsWith('.dart');
    setState(() {});
  }
}
